// pages/community/community.js
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    searchKeyword: '',
    currentCategory: 'all',
    categories: [
      { name: '全部', value: 'all' },
      { name: '紫微斗数', value: 'ziwei' },
      { name: '易经', value: 'yijing' },
      { name: '风水', value: 'fengshui' },
      { name: '八字', value: 'bazi' },
      { name: '运势', value: 'fortune' }
    ],
    publishCategories: [
      { name: '紫微斗数', value: 'ziwei' },
      { name: '易经', value: 'yijing' },
      { name: '风水', value: 'fengshui' },
      { name: '八字', value: 'bazi' },
      { name: '运势', value: 'fortune' }
    ],
    posts: [],
    showPublishModal: false,
    newPost: {
      title: '',
      content: '',
      images: [],
      categoryIndex: 0,
      tag: 'discussion'
    },
    isLoading: false,
    hasMore: true,
    pageNum: 1,
    pageSize: 10
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 初始化云开发
    if (!wx.cloud) {
      console.error('请使用 2.2.3 或以上的基础库以使用云能力')
      return
    }
    wx.cloud.init({
      env: 'cloud1-7gnaonfy0429a3eb', // 请替换为您实际的云开发环境ID（较短的格式）
      traceUser: true
    })
    
    this.loadPosts()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 1
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.setData({
      posts: [],
      pageNum: 1,
      hasMore: true
    }, () => {
      this.loadPosts().then(() => {
        wx.stopPullDownRefresh()
      })
    })
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    if (this.data.hasMore && !this.data.isLoading) {
      this.loadPosts()
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      title: '玄学社区',
      path: '/pages/community/community'
    }
  },

  /**
   * 加载帖子列表
   */
  async loadPosts() {
    if (this.data.isLoading) return
    
    this.setData({ isLoading: true })
    
    try {
      const { currentCategory, searchKeyword, pageNum, pageSize } = this.data
      const db = wx.cloud.database()
      const _ = db.command
      
      // 构建查询条件
      const query = {}
      if (currentCategory !== 'all') {
        query.category = currentCategory
      }
      if (searchKeyword) {
        query.title = db.RegExp({
          regexp: searchKeyword,
          options: 'i'
        })
      }
      
      // 查询数据
      const res = await db.collection('posts')
        .where(query)
        .orderBy('createTime', 'desc')
        .skip((pageNum - 1) * pageSize)
        .limit(pageSize)
        .get()
      
      // 处理数据
      const newPosts = res.data.map(post => ({
        id: post._id,
        username: post.author.nickname,
        avatar: post.author.avatar,
        title: post.title,
        content: post.content,
        images: post.images,
        category: post.category,
        categoryName: post.categoryName,
        createTime: new Date(post.createTime).toLocaleString(),
        likes: post.likes,
        comments: post.comments,
        tag: post.tag
      }))
      
      // 获取总数
      const countResult = await db.collection('posts').where(query).count()
      const hasMore = this.data.posts.length + newPosts.length < countResult.total
      
      this.setData({
        posts: [...this.data.posts, ...newPosts],
        pageNum: this.data.pageNum + 1,
        hasMore,
        isLoading: false
      })
    } catch (error) {
      console.error('加载帖子失败:', error)
      this.setData({ isLoading: false })
      wx.showToast({
        title: '加载失败，请重试',
        icon: 'none'
      })
    }
  },

  /**
   * 搜索帖子
   */
  onSearchInput(e) {
    this.setData({
      searchKeyword: e.detail.value
    }, () => {
      this.setData({
        posts: [],
        pageNum: 1,
        hasMore: true
      }, () => {
        this.loadPosts()
      })
    })
  },

  /**
   * 切换分类
   */
  switchCategory(e) {
    const category = e.currentTarget.dataset.category
    if (category === this.data.currentCategory) return
    
    this.setData({
      currentCategory: category,
      posts: [],
      pageNum: 1,
      hasMore: true
    }, () => {
      this.loadPosts()
    })
  },

  /**
   * 显示发布模态框
   */
  showPublishModal() {
    this.setData({
      showPublishModal: true,
      newPost: {
        title: '',
        content: '',
        images: [],
        categoryIndex: 0,
        tag: 'discussion'
      }
    })
  },

  /**
   * 隐藏发布模态框
   */
  hidePublishModal() {
    this.setData({
      showPublishModal: false
    })
  },

  /**
   * 输入标题
   */
  onTitleInput(e) {
    this.setData({
      'newPost.title': e.detail.value
    })
  },

  /**
   * 输入内容
   */
  onContentInput(e) {
    this.setData({
      'newPost.content': e.detail.value
    })
  },

  /**
   * 选择分类
   */
  onCategoryChange(e) {
    this.setData({
      'newPost.categoryIndex': e.detail.value
    })
  },

  /**
   * 选择图片
   */
  async chooseImage() {
    try {
      const res = await wx.chooseImage({
        count: 9 - this.data.newPost.images.length,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera']
      })
      
      this.setData({
        'newPost.images': [...this.data.newPost.images, ...res.tempFilePaths]
      })
    } catch (error) {
      console.error('选择图片失败:', error)
    }
  },

  /**
   * 删除图片
   */
  deleteImage(e) {
    const index = e.currentTarget.dataset.index
    const images = [...this.data.newPost.images]
    images.splice(index, 1)
    this.setData({
      'newPost.images': images
    })
  },

  /**
   * 上传图片到云存储
   */
  async uploadImages(images) {
    if (!images || images.length === 0) return []
    
    const uploadTasks = images.map(filePath => {
      return wx.cloud.uploadFile({
        cloudPath: `posts/${Date.now()}-${Math.floor(Math.random() * 1000)}.${filePath.match(/\.(\w+)$/)[1]}`,
        filePath
      })
    })
    
    try {
      const results = await Promise.all(uploadTasks)
      return results.map(res => res.fileID)
    } catch (error) {
      console.error('上传图片失败:', error)
      wx.showToast({
        title: '图片上传失败',
        icon: 'none'
      })
      return []
    }
  },

  /**
   * 发布帖子到云数据库
   */
  async publishPost() {
    const { title, content, images, categoryIndex, tag } = this.data.newPost
    const category = this.data.categories[categoryIndex]
    
    if (!title.trim()) {
      wx.showToast({
        title: '请输入标题',
        icon: 'none'
      })
      return
    }
    
    if (!content.trim()) {
      wx.showToast({
        title: '请输入内容',
        icon: 'none'
      })
      return
    }
    
    wx.showLoading({
      title: '发布中...',
      mask: true
    })
    
    try {
      // 上传图片到云存储
      const fileIDs = await this.uploadImages(images)
      
      // 获取用户信息
      const userInfo = await wx.cloud.callFunction({
        name: 'getUserInfo'
      }).catch(() => ({ result: { openid: 'anonymous' } }))
      
      // 创建帖子数据
      const postData = {
        title: title.trim(),
        content: content.trim(),
        images: fileIDs,
        category: category.value,
        categoryName: category.name,
        tag: tag,
        createTime: new Date(),
        updateTime: new Date(),
        likes: 0,
        comments: 0,
        views: 0,
        author: {
          openid: userInfo.result.openid,
          nickname: '匿名用户',
          avatar: '/assets/images/default-avatar.png'
        }
      }
      
      // 添加到云数据库
      const db = wx.cloud.database()
      const result = await db.collection('posts').add({
        data: postData
      })
      
      // 创建新帖子对象用于本地显示
      const newPost = {
        id: result._id,
        username: postData.author.nickname,
        avatar: postData.author.avatar,
        title: postData.title,
        content: postData.content,
        images: postData.images,
        category: postData.category,
        categoryName: postData.categoryName,
        createTime: postData.createTime.toLocaleString(),
        likes: postData.likes,
        comments: postData.comments,
        tag: postData.tag
      }
      
      // 更新本地数据
      this.setData({
        posts: [newPost, ...this.data.posts],
        showPublishModal: false
      })
      
      wx.hideLoading()
      wx.showToast({
        title: '发布成功',
        icon: 'success'
      })
    } catch (error) {
      console.error('发布帖子失败:', error)
      wx.hideLoading()
      wx.showToast({
        title: '发布失败，请重试',
        icon: 'none'
      })
    }
  },

  /**
   * 查看帖子详情
   */
  viewPost(e) {
    const postId = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/post-detail/post-detail?id=${postId}`
    })
  },

  previewImage(e) {
    const { urls, current } = e.currentTarget.dataset
    wx.previewImage({
      urls,
      current
    })
  },

  // 选择标签
  selectTag(e) {
    const tag = e.currentTarget.dataset.tag
    this.setData({
      'newPost.tag': tag
    })
  }
})